package com.sk.bilibili.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewbinding.ViewBinding;

import com.sk.bilibili.R;
import com.sk.bilibili.dto.GenericInfo;
import com.sk.bilibili.model.BaseModel;
import com.sk.bilibili.utils.DataUtils;
import com.sk.bilibili.utils.GenericUtils;
import com.sk.bilibili.view.BaseView;
import java.lang.reflect.Method;

import lombok.SneakyThrows;

public abstract class BaseActivity<T extends ViewBinding,M extends BaseModel>
        extends AppCompatActivity implements BaseView {

    protected T bind;//视图
    protected M model;//数据

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
        beforeSetView();
        setContentView(bind.getRoot());
        afterSetView();
        model.loadData();
    }

    protected void beforeSetView(){
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(getResources().getColor(R.color.pink_500,getTheme()));
        setTheme(DataUtils.getTheme());
    }

    protected abstract void afterSetView();

    @SneakyThrows
    private void init(){
        GenericInfo<T, M> info = GenericUtils.parse(getClass());
        // initBind
        Class<T> bindClass = info.getBindClass();
        Method inflate = bindClass.getDeclaredMethod("inflate", LayoutInflater.class);
        bind= (T) inflate.invoke(null,getLayoutInflater());
        // initModel
        Class<M> modelClass= info.getModelClass();
        model= modelClass.newInstance();
        model.setView(this);
    }

    protected void startActivity(Class<?extends BaseActivity> clazz) {
        startActivity(clazz,false);
    }

    protected void startActivity(Class<?extends BaseActivity> clazz,boolean finish) {
        startActivity(new Intent(this,clazz));
        if(finish)finish();
    }

    protected void toast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void loadError() {
        Toast.makeText(this, "加载出错了!", Toast.LENGTH_SHORT).show();
    }

}